package cn.jishiyu11.xeqb.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.provider.ContactsContract
import android.view.Gravity
import android.widget.Toast
import cn.jishiyu11.xeqb.R
import cn.jishiyu11.xeqb.activity.MainActivity
import cn.jishiyu11.xeqb.activity.LogoActivity
import cn.jishiyu11.xeqb.activity.personalCenterActivitys.RealNameActivity
import cn.jishiyu11.xeqb.http.http.i.httpbase.SERVICENAME
import cn.jishiyu11.xeqb.utils.AppUtil.getInstance
import cn.jishiyu11.xeqb.utils.systemUtils.CTelephoneInfo
import cn.sharesdk.framework.Platform
import cn.sharesdk.onekeyshare.OnekeyShare
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.text.SimpleDateFormat
import java.util.*

//import com.google.zxing.BarcodeFormat
//import com.google.zxing.MultiFormatWriter
//import com.google.zxing.common.BitMatrix
//import com.journeyapps.barcodescanner.BarcodeEncoder

/**
 * Created by jsy_zj on 2017/12/21.
 */

//手机设备信息  手机设备号和app版本号
var PhoneInfoDeviceAndVersion: String? = null
var PhoneDeviceId: String? = null
var PhoneAppVersion: String? = null
var ApplicationMap: HashMap<String, Any>? = null
var APP_CHANNAL: String? = ""
var NetIP: String? = "0.0.0.0"
var USER_PhoneNo = ""
var USER_UserNo = ""
var USER_INVICEDCODE = ""
var DEVICETYPE = "1" //1 为android  2 ios
var mainActivity: MainActivity? = null

fun Context.showShortToast(message: String): Toast {
    var toast: Toast = Toast.makeText(this, message, Toast.LENGTH_SHORT)
    toast.setGravity(Gravity.CENTER, 0, 0)
    toast.show()
    return toast
}


fun Context.showShortToastNetError(): Toast {
    var toast: Toast = Toast.makeText(this, getString(R.string.quest_net_error), Toast.LENGTH_SHORT)
    toast.setGravity(Gravity.CENTER, 0, 0)
    toast.show()
    return toast
}



fun Context.showLongToast(message: String): Toast {
    var toast: Toast = Toast.makeText(this, message, Toast.LENGTH_LONG)
    toast.setGravity(Gravity.CENTER, 0, 0)
    toast.show()
    return toast
}


inline fun <reified T : Activity> Activity.newIntent() {
    val intent = Intent(this, T::class.java)
    startActivity(intent)
}

//获取当前版本号和手机设备id
fun getAppPhoneDeviceIdAndVersion(context: Context): String {
    PhoneAppVersion = getInstance().getVersionName(1, context)
    PhoneDeviceId = CTelephoneInfo.getPhoneUDID(context)
    PhoneDeviceId = StringUtil.getMD5String(PhoneDeviceId)
    ApplicationMap = HashMap()
    ApplicationMap?.put(context.getString(R.string.versionNo), PhoneAppVersion!!)
//    NetIP = NetWorkUtils.getNetIp()
    APP_CHANNAL = getInstance().getChannel(context, 2)
    return "&userUUID=$PhoneDeviceId&version=$PhoneAppVersion"
}


//请求统配 参数   APP版本号 和 用户编号
fun getAppViersionAndUserNo(context: Context): HashMap<String, Any> {
    if (ApplicationMap?.size != 0) {
        ApplicationMap?.clear()
    }
    ApplicationMap?.put(context.getString(R.string.versionNo), PhoneAppVersion!!)
    ApplicationMap?.put(context.getString(R.string.source), 20)
    ApplicationMap?.put(context.getString(R.string.deviceType), DEVICETYPE)
    ApplicationMap?.put(context.getString(R.string.IPAddress), NetIP.toString())
    ApplicationMap?.put(context.getString(R.string.channelNo), APP_CHANNAL.toString())
//    ApplicationMap?.put(context.getString(R.string.IPAddress), NetIP!!)
    ApplicationMap?.put(context.getString(R.string.userNo), SharedPreferencesUtils.get(context, context.getString(R.string.userNo), "0"))
    return ApplicationMap!!
}


/**
 * 注册登录用验证码使用
 * */
fun getPostMap(context: Context, ServiceName: String, map: HashMap<String, Any>, postMap: HashMap<String, Any>): HashMap<String, Any> {
    var maps = HashMap<String, Any>()

    maps.put("base", getAppViersionAndUserNo(context)!!)
    maps.put("data", map)
    var json: Any? = StringListUtils.jsonEnclose(maps)
    var jsonString: String = json.toString()
    var token = StringUtil.getUUID32()
    var key = token.substring(0, 16)
    jsonString = AESUtils.encrypt(key, jsonString)
    postMap.put("sendData", jsonString)
    postMap.put("token", token)
    postMap.put(SERVICENAME, ServiceName)
//    jsonString = AESUtils.decrypt(key,jsonString)
//    println(jsonString)
    return postMap
}
/**
 * 获取VIP剩余天数使用
 * */
fun getPostMap2(context: Context, map: HashMap<String, Any>, postMap: HashMap<String, Any>): HashMap<String, Any> {
    var maps = HashMap<String, Any>()

    maps.put("base", getAppViersionAndUserNo(context)!!)
    maps.put("data", map)
    var json: Any? = StringListUtils.jsonEnclose(maps)
    var jsonString: String = json.toString()
    var token = SharedPreferencesUtils.get(context,"token","").toString()
    var key = token.substring(0, 16)
    jsonString = AESUtils.encrypt(key, jsonString)
    postMap.put("sendData", jsonString)
    postMap.put("token", token)
    return postMap
}


/**
 *  修改密码
 * */
fun getPostMap(context: Context, ServiceName: String, map: HashMap<String, Any>, postMap: HashMap<String, Any>, token: String): HashMap<String, Any> {
    var maps = HashMap<String, Any>()

    maps.put("base", getAppViersionAndUserNo(context)!!)
    maps.put("data", map)
    var json: Any? = StringListUtils.jsonEnclose(maps)
    var jsonString: String = json.toString()
//    var token = StringUtil.getUUID32()
    var key = token.substring(0, 16)
    jsonString = AESUtils.encrypt(key, jsonString)
    postMap.put("sendData", jsonString)
    postMap.put("token", token)
    postMap.put(SERVICENAME, ServiceName)
//    jsonString = AESUtils.decrypt(key,jsonString)
//    println(jsonString)
    return postMap
}

/**
 * 获取复杂json格式  解析数据  List<Bean>
 * */
inline fun <reified T : Any> getListData(json: String): MutableList<T>? {
    val g = Gson()
    val type = object : TypeToken<MutableList<T>>() {
    }.type
    val data = g.fromJson<MutableList<T>>(json, type)
    return data
}


/**
 *特殊链接指向：
 * */

fun CheckImportantKeys(context: Context, url: String): Boolean {

    var isContains = false

    if (url.trim().contains("#News#")) {
//指向新闻列表页面
//        ToatUtils.showShort(context,"指向新闻列表页面")
        isContains = true
    } else if (url.trim().contains("#LCard#")) {
//指向信用卡
//        mainActivity?.showFragment(1)
//        ToatUtils.showShort(context,"指向信用卡")
        isContains = true
    } else if (url.trim().contains("#LoanList#")) {
//指向信贷订单中心内
//        ToatUtils.showShort(context,"指向信贷订单中心内")
        isContains = true
    } else if (url.trim().contains("#UCent#")) {
//指向个人中心
//        ToatUtils.showShort(context,"指向个人中心")
//        context.startActivity(Intent(context,LogoActivity::class.java))
        isContains = true
    } else if (url.trim().contains("#Login#")) {
        //指向登录界面
        context.startActivity(Intent(context, LogoActivity::class.java))
    } else if (url.trim().contains("#RealName#")) {
//指向实名认证
//        ToatUtils.showShort(context,"指向实名认证")
        isContains = true
        context.startActivity(Intent(context, RealNameActivity::class.java))
    } else if (url.trim().contains("#BingCard#")) {
//指向银行卡绑定
//        ToatUtils.showShort(context,"指向银行卡绑定")
        isContains = true

    } else if (url.trim().contains("#Action#")) {
//指向活动页面
//        ToatUtils.showShort(context,"指向活动页面")
        isContains = true
    }else if (url.trim().contains("#Loan#")){

        mainActivity?.showSwichFragment(1)
        isContains = true

    }else if (url.trim().contains("#Card#")){

        mainActivity?.showSwichFragment(2)
        isContains = true

    }
    return isContains
}


/**
 * 第三方分享mothed
 * */
fun Activity.showShare(title: String?, titleUrl: String?, content: String?, imgBitmap: Bitmap?,imgBitmapUrl:String?,wxUrl:String?) {
    var oks: OnekeyShare = OnekeyShare()
    //关闭授权
    oks.disableSSOWhenAuthorize()
    //分享时Notification的图标和文字  2.5.9以后的版本不     调用此方法
    //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
    //title标题，微信、QQ和QQ空间等平台使用
    if (title!=null)oks.setTitle(title)
    //titleUrl QQ和QQ空间跳转链接
    if (titleUrl!=null)oks.setTitleUrl(titleUrl)
    //text是分享文本，所有平台都需要这个字段
    if (content!=null)oks.setText(content)
    //imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//    if (imgPath != null && !imgPath.isNullOrEmpty()) oks.setImagePath(imgPath)
    //imgBitmap是图片
//    if (imgBitmap != null) oks.setImageData(imgBitmap)
    if (imgBitmapUrl!=null)oks.setImageUrl(imgBitmapUrl)
//    oks.setImageUrl("https://www.baidu.com/img/bd_logo1.png")
//    oks.setImageUrl("http://file.market.xiaomi.com/thumbnail/PNG/l114/AppStore/0937f45909e0a747875209e37f8a5f6cbc1420ff1")
    // url在微信、微博，Facebook等平台中使用
//    if (wxUrl!=null)oks.setUrl(wxUrl);
//    oks.setUrl("http://app.mi.com/details?id=cn.jishiyu11.xeqb");
//    oks.setUrl("http://f4.market.xiaomi.com/download/AppStore/0237f14901e9a447725207e37ffa5f63b50888c09/cn.jishiyu11.xeqb.apk");
    //site是分享此内容的网站名称，仅在QQ空间使用
//    oks.setSite("卡小咪")
    // siteUrl是分享此内容的网站地址，仅在QQ空间使用
//    oks.setSiteUrl("http://www.baidu.com/");
    // comment是我对这条分享的评论，仅在人人网使用
//    oks.setComment("我是测试评论文本");
    // 启动分享GUI
    oks.setShareContentCustomizeCallback(object : ShareContentCustomizeCallback{
        override fun onShare(platform: Platform?, paramsToShare: Platform.ShareParams?) {
            if ("WechatMoments".equals(platform?.getName())){
                paramsToShare?.setShareType(Platform.SHARE_WEBPAGE);
                paramsToShare?.setTitleUrl(titleUrl);
                paramsToShare?.setImageUrl(imgBitmapUrl);
                paramsToShare?.setTitle(title);
                paramsToShare?.setUrl(wxUrl);
            }
            if ("QZone".equals(platform?.getName())){
                paramsToShare?.setImageUrl(imgBitmapUrl)
                paramsToShare?.setUrl(wxUrl)
            }
            if ("Wechat".equals(platform?.getName())){
                paramsToShare?.setShareType(Platform.SHARE_WEBPAGE);
//                paramsToShare?.setTitleUrl(titleUrl);
                paramsToShare?.setImageUrl(imgBitmapUrl);
                paramsToShare?.setTitle(title);
                paramsToShare?.setUrl(wxUrl);
            }

        }
    })
    oks.show(this);

}

/**
 * 生成二维码
 * */
//fun makeQRCode(str: String): Bitmap? {
//    var bm: Bitmap? = null
//    var result: BitMatrix? = null
//    var multiFormatWriter = MultiFormatWriter()
//
//    result = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, 400, 400)
//    var barcodeEncoder = BarcodeEncoder()
//    bm = barcodeEncoder.createBitmap(result)
//
//    return bm
//}


/**
 * long 值 转时间 YYYY-MM-DD
 * */
fun makeLong4Date(currentTime:String):String {

    var data = Date(currentTime.toLong())
    val format = SimpleDateFormat("yyyy-MM-dd")
    val stringDate = format.format(data)
    return stringDate
}
